# coding=utf-8
# author=haishan09@gmail.com
import json
from django.db import models
from custom.fields import JsonifyConfigField
from dimension.models import Dimension
from aggregate.models import Aggregate
from common.provider import provider_manager


class Provider(models.Model):
    name = models.CharField('名称', max_length=64)
    label = models.CharField('说明', max_length=64)
    config = JsonifyConfigField('配置信息', default='{}', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    @property
    def dconf(self):
        return (self.config and json.loads(self.config) or {})

    def __unicode__(self):
        return self.label

    def get_instance(self):
        provider_cls = provider_manager.get_provider('cube', self.name)
        return provider_cls(self)

class Cube(models.Model):
    label = models.CharField('说明', max_length=64)
    dimensions = models.ManyToManyField(
        Dimension, 
        related_name='related_cubes', 
        blank=True)
    aggregates = models.ManyToManyField(
        Aggregate, 
        related_name='related_cubes', 
        blank=True)
    provider = models.ForeignKey(Provider)
    config = JsonifyConfigField('配置信息', default='{}', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.label

    @property
    def dconf(self):
        return json.loads(self.config  and self.config or '{}') 

    def is_dim_member(self, dim):
        if isinstance(dim, str):
            dim_name = dim
        elif isinstance(dim, unicode):
            dim_name = dim
        else:
            dim_name = dim.name
        return self.dimensions.filter(name=dim_name).first()
